﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using System.Net;

namespace SPMonsterClone
{
    public partial class Form_AddCloneJob : System.Windows.Forms.Form
    {
        bool isNewForm;
        String targetJobID;

        public Form_AddCloneJob()
        {
            InitializeComponent();
            isNewForm = true;
        }

        public Form_AddCloneJob(string JobID)
        {
            InitializeComponent();
            isNewForm = false;
            targetJobID = JobID;
        }

        /// <summary>
        /// 폼이 로드될 때
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form_AddCloneJob_Load(object sender, EventArgs e)
        {
            if (isNewForm)
            {
                radio1_1.Checked = true;
                btn_Save.Visible = true;
                btn_Update.Visible = false;
                btn_Delete.Visible = false;
            }
            else
            {
                btn_Save.Visible = false;
                btn_Update.Visible = true;
                btn_Delete.Visible = true;

                setFormValue();
            }

        }

        private void setFormValue()
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable myTable;
            myTable = db.GetDataTable("SELECT tbCloneJob.* FROM tbCloneJob Where tbCloneJob.JobID = " + targetJobID);

            tbx_JobName.Text = myTable.Rows[0]["JobName"].ToString();
            tbx_MURL.Text = myTable.Rows[0]["MasterURL"].ToString();
            tbx_MAccount.Text = myTable.Rows[0]["MasterAccount"].ToString();
            tbx_MPass.Text = myTable.Rows[0]["MasterPass"].ToString();
            tbx_SURL.Text = myTable.Rows[0]["SlaveURL"].ToString();
            tbx_SAccount.Text = myTable.Rows[0]["SlaveAccount"].ToString();
            tbx_SPass.Text = myTable.Rows[0]["SlavePass"].ToString();
            radio1_1.Checked = (myTable.Rows[0]["CloneMode"].ToString() == "OneWay") ? true : false;
            radio1_2.Checked = (myTable.Rows[0]["CloneMode"].ToString() == "Duplex") ? true : false;
            radio2_1.Checked = (myTable.Rows[0]["CloneConplict"].ToString() == "Overwrite") ? true : false;
            radio2_1.Checked = (myTable.Rows[0]["CloneConplict"].ToString() == "Preserve") ? true : false;
            radio3_1.Checked = (myTable.Rows[0]["DeleteMaster"].ToString() == "Delete") ? true : false;
            radio3_2.Checked = (myTable.Rows[0]["DeleteMaster"].ToString() == "Preserve") ? true : false;
            radio4_1.Checked = (myTable.Rows[0]["DeleteSlave"].ToString() == "Delete") ? true : false;
            radio4_2.Checked = (myTable.Rows[0]["DeleteSlave"].ToString() == "Preserve") ? true : false;
            checkBox1.Checked = (myTable.Rows[0]["SkipBrkInheritance"].ToString() == "Skip") ? true : false;
        }

        private void radio1_1_CheckedChanged(object sender, EventArgs e)
        {
            radio2_1.Enabled = false;
            radio2_2.Enabled = false;
            radio3_1.Enabled = false;
            radio3_2.Enabled = false;
            radio4_1.Enabled = false;
            radio4_2.Enabled = false;
        }

        private void radio1_2_CheckedChanged(object sender, EventArgs e)
        {
            radio2_1.Enabled = true;
            radio2_2.Enabled = true;
            radio3_1.Enabled = true;
            radio3_2.Enabled = true;
            radio4_1.Enabled = true;
            radio4_2.Enabled = true;

            radio2_1.Checked = true;
            radio3_1.Checked = true;
            radio4_1.Checked = true;
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (fnFormValidate() == true)
            {
                //입력받은 값을 저장
                SQLiteDatabase db = new SQLiteDatabase();
                Dictionary<String, String> data = new Dictionary<string, string>();
                data.Add("JobID", getNewJobID());
                data.Add("JobName", tbx_JobName.Text);
                data.Add("MasterURL", tbx_MURL.Text);
                data.Add("MasterAccount", tbx_MAccount.Text);
                data.Add("MasterPass", tbx_MPass.Text);
                data.Add("SlaveURL", tbx_SURL.Text);
                data.Add("SlaveAccount", tbx_SAccount.Text);
                data.Add("SlavePass", tbx_SAccount.Text);
                data.Add("CloneMode", radio1_1.Checked ? "OneWay" : "Duplex");
                data.Add("CloneConplict", radio2_1.Checked ? "Overwrite" : "Preserve");
                data.Add("DeleteMaster", radio3_1.Checked ? "Delete" : "Preserve");
                data.Add("DeleteSlave", radio4_1.Checked ? "Delete" : "Preserve");
                data.Add("SkipBrkInheritance", checkBox1.Checked ? "Skip" : "Include");

                try
                {
                    db.Insert("tbCloneJob", data);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                //창 닫기
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
            else
            {
                MessageBox.Show("Form Validate Error.");
            }
        }

        private string getNewJobID()
        {
            SQLiteDatabase db = new SQLiteDatabase();
            DataTable myTable;
            myTable = db.GetDataTable("SELECT JobID FROM tbCloneJob order by JobID DESC limit 1 ");

            if (myTable.Rows.Count == 0)
            {
                return "1";
            }
            else
            {
                string tmpVal = myTable.Rows[0][0].ToString();
                return (int.Parse(tmpVal) + 1).ToString();
            }
        }

        private bool fnFormValidate()
        {
            if (tbx_JobName.Text == "") return false;
            if (tbx_MAccount.Text == "") return false;
            if (tbx_MPass.Text == "") return false;
            if (tbx_MURL.Text == "") return false;
            if (tbx_SAccount.Text == "") return false;
            if (tbx_SPass.Text == "") return false;
            if (tbx_SURL.Text == "") return false;

            return true;

        }

        private void btn_Update_Click(object sender, EventArgs e)
        {
            if (fnFormValidate() == true)
            {
                SQLiteDatabase db = new SQLiteDatabase();
                Dictionary<String, String> data = new Dictionary<string, string>();
                data.Add("JobName", tbx_JobName.Text);
                data.Add("MasterURL", tbx_MURL.Text);
                data.Add("MasterAccount", tbx_MAccount.Text);
                data.Add("MasterPass", tbx_MPass.Text);
                data.Add("SlaveURL", tbx_SURL.Text);
                data.Add("SlaveAccount", tbx_SAccount.Text);
                data.Add("SlavePass", tbx_SAccount.Text);
                data.Add("CloneMode", radio1_1.Checked ? "OneWay" : "Duplex");
                data.Add("CloneConplict", radio2_1.Checked ? "Overwrite" : "Preserve");
                data.Add("DeleteMaster", radio3_1.Checked ? "Delete" : "Preserve");
                data.Add("DeleteSlave", radio4_1.Checked ? "Delete" : "Preserve");
                data.Add("SkipBrkInheritance", checkBox1.Checked ? "Skip" : "Include");

                try
                {
                    db.Update("tbCloneJob", data, String.Format("tbCloneJob.JobID = {0}", targetJobID));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                //창 닫기
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {

        }

        private void btn_ConTest1_Click(object sender, EventArgs e)
        {
            if (validateConnection(tbx_MURL.Text, tbx_MAccount.Text, tbx_MPass.Text))
            {
                using (ClientContext clientContext = new ClientContext(tbx_MURL.Text))
                {
                    clientContext.Credentials = new NetworkCredential(tbx_MAccount.Text.Split('\\')[1], tbx_MPass.Text, tbx_MAccount.Text.Split('\\')[0]);
                    //clientContext.Credentials = new NetworkCredential("spadmin", "Lan01170303", "MYSP2010");

                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();

                    MessageBox.Show(web.Title);
                }
            }
            else
            {
                MessageBox.Show("입력정보가 잘못되었습니다.");
            }
        }

        /// <summary>
        /// 쉐어포인트 연결정보를 점검한다.
        /// </summary>
        /// <param name="_URL"></param>
        /// <param name="_Account"></param>
        /// <param name="_Password"></param>
        /// <returns></returns>
        private bool validateConnection(string _URL, string _Account, string _Password)
        {
            if (_URL == "") return false;
            if (_Account == "") return false;
            if (_Account.IndexOf("\\") < 0) return false;
            if (_Password == "") return false;

            return true;
        }

        private void btn_ConTest2_Click(object sender, EventArgs e)
        {

        }
    }
}
